package com.zemb.flxwear.UI.Activity;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zemb.flxwear.Adapter.ReportAdapter;
import com.zemb.flxwear.Bean.ReportItem;
import com.zemb.flxwear.DB.DataBaseHelper;
import com.zemb.flxwear.Define.AppConst;
import com.zemb.flxwear.R;
import com.zemb.flxwear.Utils.IMEI;
import com.zemb.flxwear.Utils.LogUtils;
import com.zemb.flxwear.Utils.PDFUtils;
import com.zemb.flxwear.Utils.SharePreferencesUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class MedicalReportActivity extends AppCompatActivity implements View.OnClickListener {
    List<ReportItem> itemList;
    ReportAdapter reportAdapter;
    RecyclerView recyclerView;
    EditText phone;
    String phoneNum;
    ConstraintLayout loading;
    Button btnShare;
    int uid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medical_report);
        initData();
        initView();
    }

    void initData() {
        itemList = (List<ReportItem>) getIntent().getSerializableExtra("reportItems");
        phoneNum = SharePreferencesUtils.getInstance().getString("phone");

        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

        }
        phoneNum = tm.getLine1Number();//获取本机号码

    }

    void initView() {
        recyclerView = findViewById(R.id.rc_report);
        reportAdapter = new ReportAdapter(this);
        loading = findViewById(R.id.include);
        btnShare = findViewById(R.id.btn_share);
        btnShare.setOnClickListener(this);
        phone = findViewById(R.id.tv_user_name);
        if (phoneNum != null && !phoneNum.isEmpty()) {
            phone.setText(phoneNum);
        }

        if (itemList == null) {
            //在数据库里面查询
            // TODO: 2023/5/5
            new AsyncTask<Void, Void, List<ReportItem>>() {
                @Override
                protected List<ReportItem> doInBackground(Void... params) {
                    // 执行查询操作，返回游标对象
                    List<ReportItem> list = new ArrayList<>();
                    list.add(DataBaseHelper.getInstance(MedicalReportActivity.this).queryBPFirstByUid(uid));
                    list.add(DataBaseHelper.getInstance(MedicalReportActivity.this).queryBOFirstByUid(uid));
                    list.add(DataBaseHelper.getInstance(MedicalReportActivity.this).queryBSFirstByUid(uid));
                    list.add(DataBaseHelper.getInstance(MedicalReportActivity.this).queryBKFirstByUid(uid));
                    list.add(DataBaseHelper.getInstance(MedicalReportActivity.this).queryCHOLFirstByUid(uid));
                    list.add(DataBaseHelper.getInstance(MedicalReportActivity.this).queryUAFirstByUid(uid));
                    ReportItem reportItem = DataBaseHelper.getInstance(MedicalReportActivity.this).queryECGFirstByUid(uid);
                    reportItem.result = "Please check on the webpage";
                    list.add(reportItem);
                    return list;
                }

                @Override
                protected void onPostExecute(List<ReportItem> list) {
                    // 在 UI 线程中更新 UI
                    itemList = list;
                    reportAdapter.setList(list);
                }
            }.execute();
        } else {
            reportAdapter.setList(itemList);
        }
        //设置垂直滚动
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(reportAdapter);
        if (phoneNum != null) {
            phone.setText(phoneNum);
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_share) {
            if (!phone.getText().toString().isEmpty()) {
                phoneNum = phone.getText().toString();
                SharePreferencesUtils.getInstance().putString("phone", phoneNum);
                Thread thread = new Thread(() -> {
                    //校验手机号
                    uploadLogFile(itemList);
                });
                thread.start();
            } else {
                //提示输入手机号
                Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void uploadLogFile(List<ReportItem> itemList) {
        runOnUiThread(() -> loading.setVisibility(VISIBLE));
        PDFUtils pdfUtils = new PDFUtils(this);
        String fileName = phone.getText() + "_" + System.currentTimeMillis() + "" + ".pdf";
        LogUtils.PrintLog("fileName" + fileName);
        pdfUtils.createPDFInThread(this.getFilesDir().toString(), fileName, itemList, phoneNum);
//            bloodPressure  血压 (高压/低压)格式
//            heartRate 心率
//            bloodOxygen  血酮
//            pulse 脉搏
//            uricAcid 尿酸
//            bloodSugar 血糖
//            cholesterol 胆固醇
//            bloodKetone 血氧
//        StringBuilder link = new StringBuilder(AppConst.upload + fileName + "&fileType=pdf" + "&imei=" + IMEI.getDeviceId(MedicalReportActivity.this));
//        for (ReportItem reportItem : itemList) {
//            switch (reportItem.type) {
//                case BLOOD_PRESSURE:
//                    link.append("&bloodPressure=").append(reportItem.result);
//                    break;
//                case BLOOD_OXYGEN:
//                    link.append("&bloodOxygen=").append(reportItem.result);
//                    break;
//                case BLOOD_SUGAR:
//                    link.append("&bloodSugar=").append(reportItem.result);
//                    break;
//                case BLOOD_KETONE:
//                    link.append("&bloodKetone=").append(reportItem.result);
//                    break;
//                case CHOLESTEROL:
//                    link.append("&cholesterol=").append(reportItem.result);
//                    break;
//                case URIC_ACID:
//                    link.append("&uricAcid=").append(reportItem.result);
//                    break;
//            }
//        }
        String link = AppConst.upload+ fileName + "&fileType=pdf" +"&imei="+IMEI.getDeviceId(MedicalReportActivity.this)+
                "&bloodPressure=" + 0+
                "/" + 0 +
                "&heartRate=" + 0
                + "&bloodOxygen=" +0
                +"&uricAcid="+0
                + "&pulse=" + 0
                + "&bloodSugar=" + 0
                + "&cholesterol=" + 0
                +"&bloodKetone="+0;
        File file = new File(getFilesDir(), fileName);

        uploadLogFile(this, link.toString(), file.getAbsolutePath());

    }

    public void uploadLogFile(Context context, String link, String filePath) {
//        try {
//            OkHttpClient client = new OkHttpClient(); // 创建OkHttpClient对象
//
//            // 构建请求体
//            RequestBody requestBody = new MultipartBuilder()
//                    .type(MultipartBuilder.FORM)
//                    .addFormDataPart("file", "file.pdf", RequestBody.create(MediaType.parse("application/pdf"), new File(filePath)))
//                    .build();
//            // 构建请求对象
//            Request request = new Request.Builder()
//                    .url(url)
//                    .post(requestBody)
//                    .build();
//
//            // 发送请求并获取响应
//            Response response = client.newCall(request).execute();
//            if (!response.isSuccessful()) {
//                runOnUiThread(() -> {
//                    loading.setVisibility(GONE);
//                    Toast.makeText(context, "Upload Failed", Toast.LENGTH_SHORT).show();
//                });
//                throw new IOException("Unexpected code " + response);
//            }
//
//            runOnUiThread(() -> {
//                loading.setVisibility(GONE);
//                Toast.makeText(context, "UpLoad Success", Toast.LENGTH_SHORT).show();
//                    });
//            // 处理响应结果
//            String responseString = response.body().string();
//        }catch (Exception e){
//            e.printStackTrace();
//            runOnUiThread(() -> {
//                loading.setVisibility(GONE);
//                Toast.makeText(context, "UpLoad Failed", Toast.LENGTH_SHORT).show();
//            });
//        }
        try {
            URL url = new URL(link);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 允许Input、Output，不使用Cache
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);

            con.setConnectTimeout(50000);
            con.setReadTimeout(50000);
            // 设置传送的method=POST
            con.setRequestMethod("POST");
            //在一次TCP连接中可以持续发送多份数据而不会断开连接
            con.setRequestProperty("Connection", "Keep-Alive");
            //设置编码
            con.setRequestProperty("Charset", "UTF-8");
            //text/plain能上传纯文本文件的编码格式
            con.setRequestProperty("Content-Type", "text/plain");

            // 设置DataOutputStream
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());

            // 取得文件的FileInputStream
            FileInputStream fStream = new FileInputStream(filePath);
            // 设置每次写入1024bytes
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            int length = -1;
            // 从文件读取数据至缓冲区
            while ((length = fStream.read(buffer)) != -1) {
                // 将资料写入DataOutputStream中
                ds.write(buffer, 0, length);
            }
            ds.flush();
            fStream.close();
            ds.close();
            Log.d("dfr1111", con.toString());

            if (con.getResponseCode() == 200) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loading.setVisibility(GONE);
                        Toast.makeText(MedicalReportActivity.this, "文件上传成功！", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            final Exception a = e;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loading.setVisibility(GONE);
                    Toast.makeText(MedicalReportActivity.this, "文件上传失败！错误：" + a.toString(), Toast.LENGTH_SHORT).show();

                }
            });

            Log.d("dfr1111", "报错信息toString：" + e.toString());
        }

    }


}

